package activity


import android.Manifest
import android.animation.ValueAnimator
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Rect
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.view.animation.Animation
import android.view.animation.TranslateAnimation
import android.widget.Button
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.hontech.pizzav2.R
import event.*
import ext.log
import manager.*
import mvc.model.Status
import mvc.model.view.MenuView
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import popup.*
import task.MatchResetTask
import task.RefreshSellTask
import view.CustomMediaPlayer
import view.MenuItemView

class MainActivity : AppCompatActivity() {
    companion object {
        const val PERMISSION_REQUEST = 0x01
        const val QUIT_ACTION = "quit.action"
        var isShow = true
    }

    private val mTopPlayer: CustomMediaPlayer by lazy {
        findViewById<CustomMediaPlayer>(R.id.id_main_player_top)
    }
    private val mBottomPlayer: CustomMediaPlayer by lazy {
        findViewById<CustomMediaPlayer>(R.id.id_main_player_bottom)
    }
    private val mRecyclerView: RecyclerView by lazy {
        findViewById<RecyclerView>(R.id.id_main_recycler_view)
    }

/*    private val mImageViewBounce: ImageView by lazy {
        findViewById<ImageView>(R.id.id_main_image_point)
    }*/

    private val mImageViewQr: ImageView by lazy {
        findViewById<ImageView>(R.id.id_main_qr_image_view)
    }

    private val mButtonDebug: Button by lazy { findViewById<Button>(R.id.id_main_button_debug) }
    private lateinit var mRecyclerViewAdapter: RecyclerViewAdapter
    private lateinit var mAutoScrollAnim: RecyclerViewAutoScrollManager

/*    private lateinit var mBounceAnim: Animation*/

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        requestPermission()
        initDeviceQrCode()
    }

    private fun initDeviceQrCode() {
        val bitmap = createQrcodeBitmap(AppManager.getWebAppQrUrl(), 250, 250)
        mImageViewQr.setImageBitmap(bitmap)
    }

    override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)
        if (hasFocus) {
            EventBus.getDefault().post(SellChangedEvent(RefreshSellTask.SellStatus))
        }
    }

    override fun onResume() {
        super.onResume()
        isShow = true
        mTopPlayer.onResume()
        mBottomPlayer.onResume()
        EventBus.getDefault().post(SellChangedEvent(RefreshSellTask.SellStatus))

        mRecyclerViewAdapter.notifyDataSetChanged()
        if (WaresManager.InventoryWaresCargo.size > 0) {
            mAutoScrollAnim.start()
        }
    }

    override fun onPause() {
        super.onPause()
        isShow = false
        mTopPlayer.onPause()
        mBottomPlayer.onPause()
        mAutoScrollAnim.stop()
    }

    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        val flag = intent.getBooleanExtra(QUIT_ACTION, false)
        if (flag) {
            finish()
        }
    }

    private fun onClickDebug(view: View): Boolean {
        UserLoginWindow.Instance.show(mRecyclerView)
        return true
    }

    private fun requestPermission() {
        val ret = ActivityCompat.checkSelfPermission(
            this,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
        )
        if (ret != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(
                this,
                arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), PERMISSION_REQUEST
            )
        } else {
            onInit()
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int, permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)

        if (requestCode == PERMISSION_REQUEST && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            onInit()
        }
    }

    private fun onInit() {
        mRecyclerViewAdapter = RecyclerViewAdapter(::onItemClick)
        mRecyclerView.adapter = mRecyclerViewAdapter
        mRecyclerView.layoutManager = LinearLayoutManager(
            this, LinearLayoutManager.HORIZONTAL,
            false
        )
        mRecyclerView.addItemDecoration(RecyclerViewItemDecoration())
        mAutoScrollAnim = RecyclerViewAutoScrollManager(mRecyclerView)
        mTopPlayer.onCompletion = ::onTopComplete
        mBottomPlayer.onCompletion = ::onBottomComplete

        mButtonDebug.setOnLongClickListener(::onClickDebug)

/*        mBounceAnim = TranslateAnimation(
            TranslateAnimation.RELATIVE_TO_SELF, 0f,
            TranslateAnimation.RELATIVE_TO_SELF, 0f,
            TranslateAnimation.RELATIVE_TO_SELF, 0f,
            TranslateAnimation.RELATIVE_TO_SELF, 0.2f
        )
        mBounceAnim.duration = 500
        mBounceAnim.repeatCount = Animation.INFINITE
        mBounceAnim.repeatMode = Animation.REVERSE
        mImageViewBounce.startAnimation(mBounceAnim)*/
    }

    override fun onStart() {
        super.onStart()
        EventBus.getDefault().register(this)
    }

    override fun onStop() {
        super.onStop()
        EventBus.getDefault().unregister(this)
    }

    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
    fun onMcuOtaEvent(env: OtaProgressChanged) {
        if (env.status != OtaProgressChanged.STATUS_START) {
            return
        }
        McuOtaWindow.Instance.show(mRecyclerView)
    }

    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
    fun onInventoryChangedEvent(env: InventoryChangedEvent) // 库存发生变化
    {
        mAutoScrollAnim.stop()
        mRecyclerViewAdapter.notifyDataSetChanged()
        if (WaresManager.InventoryWaresCargo.size == 0) {
            return
        }
        mAutoScrollAnim.start()
    }

    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED) // 广告发生变化
    fun onAdvChangedEvent(env: AdvChangedEvent) {
        val top = AdvertisingManager.findTopNextMedia()
        val bottom = AdvertisingManager.findBottomNextMedia()
        mTopPlayer.setUp(top)
        mBottomPlayer.setUp(bottom)
    }

    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
    fun onChargeStatusChangedEvent(env: ChargeStatusChangedEvent) // 用户刷卡
    {
        if (env.status == ChargeStatusChangedEvent.OK) {
            PayWindow.Instance.dismiss()
            DeliveryWindow.Instance.show(mRecyclerView)
            return
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
    fun onRemoteDelivery(env: RemoteDelivery) {
        DeliveryWindow.Instance.show(mRecyclerView)
    }

    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
    fun onUserLoginChangedEvent(env: LoginChangedEvent) {
        when (env.type) {
            LoginChangedEvent.INFO -> {
                UserLoginWindow.Instance.dismiss()
                val i = Intent(this, InfoActivity::class.java)
                startActivity(i)
            }

            LoginChangedEvent.SCAN -> {
                UserLoginWindow.Instance.dismiss()
                val i = Intent(this, ScanActivity::class.java)
                startActivity(i)
            }

            LoginChangedEvent.SET -> {
                UserLoginWindow.Instance.dismiss()
                val i = Intent(this, SettingActivity::class.java)
                startActivity(i)
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
    fun onStatusChangedEvent(env: StatusChangedEvent) {

        if (env.status.externPushMotor != Status.OK) {
            AsyncTask.postDelayed(MatchResetTask(), 5 * 1000)
        }

        if (MY_LOCATION == LOCATION_US) {

            val ret = String.format(
                "Fridge:%.1f℉\r\nOven:%.1f℉",
                env.status.fridgeTempValue() * 1.8f + 32,
                (env.status.ovenTempValue) * 1.8f + 32
            )
            mButtonDebug.text = ret

        } else if (MY_LOCATION == LOCATION_UK) {
            val ret = String.format(
                "Fridge:%.1f℃\r\nOven:%d℃",
                env.status.fridgeTempValue(),
                (env.status.ovenTempValue)
            )
            mButtonDebug.text = ret
        }

        if (env.changed && ((!AppManager.isBusy) || DeliveryWindow.isShow)) {
            if (env.status.isFault) {
                FaultWindow.Instance.showWithTitle(env.status.faultMessage, mRecyclerView)
            } else {
                FaultWindow.Instance.dismiss()
            }
            return
        }
        if (!env.status.isFault) {
            FaultWindow.Instance.dismiss()
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
    fun onSellChangedEvent(env: SellChangedEvent) {
        if (AppManager.isBusy) {
            return
        }
        if (env.status == SellChangedEvent.START) {
            SellPopupWindow.Instance.dismiss()
        } else if (env.status == SellChangedEvent.STOP) {
            SellPopupWindow.Instance.show(mRecyclerView)
        }
    }

    private fun onTopComplete() {
        val top = AdvertisingManager.findTopNextMedia()
        mTopPlayer.setUp(top)
    }

    private fun onBottomComplete() {
        val bottom = AdvertisingManager.findBottomNextMedia()
        mBottomPlayer.setUp(bottom)
    }

    private fun onItemClick(position: Int) {
        if (StatusManager.status.isFault) {
            FaultWindow.Instance.showWithTitle(StatusManager.status.faultMessage, mRecyclerView)
            return
        }
        WaresManager.SelectIndex = position
        PayWindow.Instance.show(mRecyclerView)
    }

    private class RecyclerViewAutoScrollManager(val recyclerView: RecyclerView) : Runnable {

        override fun run() {
            recyclerView.scrollBy(1, 0)
            AppTask.postDelayed(this, 100)
        }

        fun start() {
            log("启动动画")
            AppTask.postDelayed(this, 100)
        }

        fun stop() {
            log("停止动画")
            AppTask.removeCallbacks(this)
            recyclerView.scrollToPosition(0)
        }
    }

    private class RecyclerViewAdapter(val onItemClick: (Int) -> Unit) :
        RecyclerView.Adapter<MenuView>() {

        override fun onBindViewHolder(holder: MenuView, position: Int) {
            val p = position % WaresManager.InventoryWaresCargo.size
            val info = WaresManager.InventoryWaresCargo[p]
            holder.menuItem.setWaresInfo(info, onItemClick, p)
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MenuView {
            return MenuView(MenuItemView(parent.context))
        }

        override fun getItemCount(): Int {
            val number = WaresManager.InventoryWaresCargo.size
            if (number <= 0) {
                return 0
            }
            return Int.MAX_VALUE
        }
    }

    private class RecyclerViewItemDecoration : RecyclerView.ItemDecoration() {
        override fun getItemOffsets(outRect: Rect, itemPosition: Int, parent: RecyclerView) {
            super.getItemOffsets(outRect, itemPosition, parent)
            outRect.left = 5
            outRect.top = 5
        }
    }
}
